from flask import Flask, request, render_template, url_for, session
from markupsafe import escape
import os
from datetime import timedelta

app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(30)  # 随机Key，用来加密
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(hours=2)  # 设置session过期时间为2h


@app.route('/')
def hello():
    session['username'] = 'Nancy'  # 设置session
    session.permanent = True  # 默认False，若设为True，则会存储31天
    return 'Hello,World!'


@app.route('/get_session/')
def get_session():
    username = session.get('username', '没有获取到username')  # 获取session
    return f'获取的session为：{username}'


@app.route('/del_session/')
def del_session():
    session.pop('username')  # 删除session
    # session.clear()  # 删除session中所有的值
    return f'删除session成功'


if __name__ == "__main__":
    app.run(port=5000, host="127.0.0.1", debug=True)
